package com.hotau.push;

import java.util.Timer;
import java.util.TimerTask;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;

import com.hotau.HotauActivity;
import com.hotau.HotauConstants;
import com.hotau.R;
import com.hotau.member.service.MemberService;
import com.hotau.util.HttpUtil;
import com.hotau.util.PreferencesUtils;

public class PushService extends Service {
	public static final String TAG = "PushService";

	private Timer timer = null;
	public static final int PERIOD = 60 * 1000;
	private Handler mHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			super.handleMessage(msg);
			
			String usrCode = MemberService.getUserCode(PushService.this);
			Log.d("mytag", "推送服务获取的usrCode：" + usrCode);
			
			if (usrCode == null || "".equals(usrCode)) {
				return;
			}
			
			String request = "Form:userCode=" + usrCode + ";terminalCode=" + HotauConstants.getTerminalCode
                    (PushService.this.getApplicationContext());
			
			Log.d(TAG, "push request: " + request);
			
			// 轮询发送请求 查看是否有订单未支付的
			String result = HttpUtil.doHttp(60000, 60000,HotauConstants.PUSH_URL,
                request
					,
					HttpUtil.HTTP_POST, HttpUtil.UTF8_ENCODING, false);
			// "+MemberService.getToken(PushService.this)+"
			Log.d(TAG, "PushService_response :" + result);

			if (result == null) {
				return;
			}

			// 解析返回数据 判断是否提示用户
			try {
				JSONObject push_result = new JSONObject(result);
				if (push_result != null && push_result.getInt("result") == 1) {
					if (push_result.getInt("isPush") == 1) {
						// 通知
						String receive = PreferencesUtils
								.getReceive(PushService.this);
						if ("1".equals(receive)) {
							startNotification();
						}

						// 弹出对话框 的重新实现
					}
				}
			} catch (JSONException e) {

			}
		}

	};

	@Override
	public IBinder onBind(Intent arg0) {

		Log.e(TAG, "onBind");

		return null;

	}

	@Override
	public boolean onUnbind(Intent intent) {

		super.onUnbind(intent);

		Log.e(TAG, "onUnbind");

		return false;

	}

	@Override
	public void onCreate() {

		super.onCreate();
		timer = new Timer();
		Log.e(TAG, "onCreate");

	}

	@Override
	public void onDestroy() {

		super.onDestroy();
		if (timer != null) {
			timer.cancel();
		}
		Log.e(TAG, "onDestroy");

	}

	@Override
	public void onStart(Intent intent, int startId) {

		super.onStartCommand(intent, 0, startId);
		
		Log.e(TAG, "onStart");
		String value = PreferencesUtils.getReceive(this.getApplicationContext());
		if (PreferencesUtils.VALUE_PUSH_ON.equals(value)) {

			timer.schedule(new TimerTask() {
	
				@Override
				public void run() {
	
					mHandler.sendEmptyMessage(0);
				}
	
			}, 0, PERIOD);
		} else 
			this.stopSelf();
	}

	public void startNotification() {
		// 消息通知栏

		// 定义NotificationManager

		String ns = Context.NOTIFICATION_SERVICE;

		NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);

		// 定义通知栏展现的内容信息

		int icon = R.drawable.icon;

		CharSequence tickerText = "您有未处理的订单！";

		long when = System.currentTimeMillis();

		Notification notification = new Notification(icon, tickerText, when);

		// 定义下拉通知栏时要展现的内容信息

		Context context = getApplicationContext();

		CharSequence contentTitle = "新订单";

		CharSequence contentText = "未处理的订单";

		// TODO
		Intent notificationIntent = new Intent(context, HotauActivity.class);
		notificationIntent.putExtra("Type", "1");
		

		PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
				notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
		notification.flags = 
		        (Notification.FLAG_SHOW_LIGHTS | Notification.FLAG_AUTO_CANCEL);

		notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
		
		Log.d("mytag", "通知。。。。。。contentIntent＝" + contentIntent);

		// 用mNotificationManager的notify方法通知用户生成标题栏消息通知
		//		mNotificationManager.cancel(1);
		mNotificationManager.notify(1, notification);

	}

}
